package com.base.vistter.iframe.inverter.controller;

import com.base.vistter.iframe.bean.Result;
import com.base.vistter.iframe.exception.IframeException;
import com.base.vistter.iframe.model.location.LocationResponse;
import com.base.vistter.iframe.service.LocationService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequestMapping("/location")
public class LocationController {
    @Resource(name = "locationService")
    private LocationService locationService;

    @GetMapping
    public Result<LocationResponse> get(HttpServletRequest request) throws IframeException {
        String ip = getRomortIP(request);
        if(StringUtils.isBlank(ip)){
            throw new IframeException("获取IP地址失败");
        }
        return Result.ok(locationService.getLocation(ip));
    }


    private String getRomortIP(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if(ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)){
            ip = request.getHeader("X-Real-IP");
        }
        return ip;
    }

}
